package com.emm.yixun.website.controller.marketing;

//框架包
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.anotations.AvoidDuplicateSubmission;
import com.emm.yixun.anotations.UserOperateLog;
import com.emm.yixun.common.enums.FunctionTypeEnum;
import com.emm.yixun.common.enums.ModelTypeEnum;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.SubscribeInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ActNodeDataDto;
import com.emm.yixun.common.model.dto.ActNodeQuery;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BaseCodeTypeEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.SubscribeBusinessStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.estate.service.ActNodeDataServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectSettingServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.ImageServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.ao.DataService.OaDataService;
import com.emm.yixun.website.service.image.WsImageService;
import com.emm.yixun.website.utils.TokenProcessor;
import com.emm.yixun.website.vo.common.ExtResultVo;
//common
//website
//变化的引用

@Controller
@RequestMapping("/marketing/businessAbnorma/")
public class BusinessAbnormaController extends BaseController<BusinessAbnorma> {

	@Autowired
	private BusinessAbnormaServiceFacade businessAbnormaServiceFacade;

	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private ImageServiceFacade imageServiceFacade;
	@Autowired
	private WsImageService wsImageService;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade; 
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;
	@Autowired
	private OaDataService oaDataService;
	@Autowired
	private ActNodeDataServiceFacade actNodeDataServiceFacade;
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/marketing/businessAbnorma/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(BusinessAbnormaDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:businessAbnorma:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:businessAbnorma:view"))) {
			try {
				Response<BusinessAbnorma> response = businessAbnormaServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(BusinessAbnormaDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:businessAbnorma:edit"))) {
			try {
				Response<Integer> response = businessAbnormaServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:businessAbnorma:delete"))) {
			try {
				Response<Integer> response = businessAbnormaServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}
	/**
	 * 
	 * abnormaBusiness:(认购换房). <br/>
	 * @author Administrator
	 * @param id 认购ID
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "abnormaBusiness")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public ModelAndView abnormaBusiness(Long id,ModelMap map) {
		Subscribe subscribe =  subscribeServiceFacade.findById(id).getEntity();
		// 查询菜单按钮权限
		User user = ShiroUtil.getCurrentUser();
		map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
		map.put("userId", user.getId());
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setProjectId(subscribe.getProjectId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		map.put("subscribeId", id);
		map.put("customerProjectId",subscribe.getProjectId());
		map.put("documentType", dtArray.toJSONString());
		map.put("projectId", subscribe.getProjectId());
		return new ModelAndView("marketing/abnorma/subscribeChangeRoom")
				.addObject("userName", ShiroUtil.getCurrentUser().getUserName())
				.addObject("customerId", subscribe.getCustomerId());
	}
	
	
	
	@RequestMapping(value = "subscribeChangeRoomAdd", method = RequestMethod.POST)
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_4, modelName = ModelTypeEnum.MODELTYPE_2, roomKey = "roomId")
	public AjaxRes subscribeChangeRoomAdd(String params, Boolean startProcess, HttpServletRequest request,Long subscribeId) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:subscribe:add"))) {
			try {
				SubscribeDto paramsSubscribeDto = JSONObject.parseObject(params, SubscribeDto.class);
				Response<ProjectRoom> projectRoomResponse = projectRoomServiceFacade.findById(paramsSubscribeDto.getRoomId());
				Long projectId = projectRoomResponse.getEntity().getProjectId();
				if (null == projectId) {
					ar.setFailMsg("项目不存在!");
					return ar;
				}
				String resMsg = "换房提交成功";
				Response<SubscribeDto> response = subscribeServiceFacade.addSubscribe(params, user,subscribeId);
				if (response.isSuccess()) {
					SubscribeDto subscribeDto = response.getEntity();
					//发起认购换房审核
					String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,ProcessTypeEnums.PROCESS_KEY_7);
					String processDefinitionKey = startProcessKey;
					boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,processDefinitionKey);
					if (!isSeting) {
						ar.setFailMsg("认购换房审批流程节点人员未设置");
						return ar;
					}
					//保存认购换房记录
					BusinessAbnormaDto dto = new BusinessAbnormaDto();
					dto.setBusinessId(subscribeId); //原认购记录ID
					dto.setNewRoomId(paramsSubscribeDto.getRoomId());
					Response<Long> busResponse = businessAbnormaServiceFacade.saveChangeHouseInfo(user, dto);
					identityService.setAuthenticatedUserId(user.getUserAccount());
					String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,processDefinitionKey, subscribeId.toString(), null);
					BusinessAbnormaDto updateDto=new BusinessAbnormaDto();
					updateDto.setId(busResponse.getEntity());
					updateDto.setProcInstId(pid);
					updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					updateDto.setCheckDate(new Date());
					businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
					//添加流程审核需要的图片
					wsImageService.uploadAttachment(paramsSubscribeDto.getFileArr(), String.valueOf(subscribeDto.getId()), paramsSubscribeDto.getImageType(), subscribeDto.getProjectCode());
					ar.setObj(response.getEntity().getId());
					ar.setRes(Const.SUCCEED);
					ar.setResMsg(resMsg);
				} else {
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception ex) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "新增认购换房", params, JSONObject.toJSONString(ex));
				
				logger.error("新增认购换房错误", ex);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}
	
	@RequestMapping(value = "isChangeHouse", method = RequestMethod.POST)
	public @ResponseBody AjaxRes isChangeHouse(Long abnormaId) {
		AjaxRes ar = getAjaxRes();
		try {
			BusinessAbnormaDto dto = new BusinessAbnormaDto();
			dto.setBusinessId(abnormaId);
			dto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
			Response<Boolean> response = businessAbnormaServiceFacade.selectByDto(dto);
			if (!response.isSuccess()) {
				ar.setRes(Const.FAIL);
				ar.setResMsg(response.getResultMessage());
			} else {
				ar.setRes(Const.SUCCEED);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setRes(10000);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	@RequestMapping(value = "subscribeChangeRoomById")
	public @ResponseBody ExtResultVo subscribeChangeRoomById(Long id) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		SubscribeInfo subscribeInfo = subscribeServiceFacade.findByIdInfo(id).getEntity();
		Customer cusomter = customerServiceFacade.findById(subscribeInfo.getCustomerId()).getEntity();
		subscribeInfo.setCustomerName(cusomter.getCustomerName());
		Response<BigDecimal> haveAmountEntity = haveReceiveRefundServiceFacade.findSubscribeHaveAmount(id);
		if(haveAmountEntity.getEntity()!=null){
			subscribeInfo.setReceivedPayAmount(haveAmountEntity.getEntity());
		}else{
			subscribeInfo.setReceivedPayAmount(BigDecimal.ZERO);
		}
		subscribeInfo.setCheckDateStr(DateUtils.DateToString(subscribeInfo.getCheckDate(), DateStyle.YYYY_MM_DD_CN.getValue()));
		ProjectRoom room = projectRoomServiceFacade.findById(subscribeInfo.getRoomId()).getEntity();
		subscribeInfo.setComboxRoomName(room.getCombinedName());
		vo.setData(subscribeInfo);
		return vo;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes list(BusinessAbnormaDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:businessAbnorma:list"))) {
			try {
				Page<BusinessAbnorma> response = businessAbnormaServiceFacade.findPageByDto(dto,
						PageUtil.begin(pageNum, pageSize), pageSize);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<BusinessAbnorma>());
					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 新增返回实体对象
	@RequestMapping(value = "addChangeHouse")
	@ResponseBody
	@AvoidDuplicateSubmission(needRemoveToken = true)
	public AjaxRes addChangeHouse(BusinessAbnormaDto dto, String fileUrlArr, String imageType, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		//操作失败时,重新刷新提交Token
		String newToken = TokenProcessor.getInstance().generateToken(request);
		request.getSession(false).setAttribute("token", newToken);
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:subscribe:changeHouse"))) {
			try {
				Response<ProjectRoom> projectRoomResponse = projectRoomServiceFacade.findById(dto.getNewRoomId());
				Long projectId = projectRoomResponse.getEntity().getProjectId();
				if (null == projectId) {
					ar.setFailMsg("项目不存在!");
					ar.setObj(newToken);
					return ar;
				}
				// 动态获取价格方案流程KEY
				String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
						ProcessTypeEnums.PROCESS_KEY_7);
				if (StringUtils.isEmpty(startProcessKey)) {
					ar.setFailMsg("项目未设置认购换房审批流程,请去项目流程菜单配置！");
					ar.setObj(newToken);
					return ar;
				}
				String processDefinitionKey = startProcessKey;
				boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,
						processDefinitionKey);
				if (!isSeting) {
					ar.setFailMsg("认购换房审批流程节点人员未设置");
					ar.setObj(newToken);
					return ar;
				}
				Response<Long> response = businessAbnormaServiceFacade.saveChangeHouseInfo(user, dto);
				if (response.isSuccess()) {
					// 启动流程
					identityService.setAuthenticatedUserId(user.getUserAccount());
					String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
							processDefinitionKey, dto.getBusinessId().toString(), null);
					
					BusinessAbnormaDto updateDto=new BusinessAbnormaDto();
					updateDto.setId(response.getEntity());
					updateDto.setProcInstId(pid);
					updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					updateDto.setCheckDate(new Date());
					businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
					

					// 保存流程附件
					if (StringUtils.isNotBlank(fileUrlArr)) {
						wsImageService.uploadAttachment(fileUrlArr, String.valueOf(dto.getBusinessId()), imageType,
								projectRoomResponse.getEntity().getAccessCode());
					}
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception ex) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "新增认购换房", JSONObject.toJSONString(dto), JSONObject.toJSONString(ex));
				
				logger.error("认购换房", ex);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		//操作失败,重置防重复提交Token
        if(Const.FAIL == ar.getRes()){
        	ar.setObj(newToken);
        }
		return ar;
	}

	public void saveProcessFile(String projectCode, String pid, String[] fileArr) {
		if (null == fileArr || fileArr.length == 0 || StringUtils.isBlank(pid) || StringUtils.isBlank(projectCode))
			return;
		User user = ShiroUtil.getCurrentUser();
		for (int ii = 0; ii < fileArr.length; ii++) {
			if (StringUtils.isNotEmpty(fileArr[ii])) {
				try {
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(Long.valueOf(pid));
					imageDto.setTitle("流程附件");
					imageDto.setContent("流程附件");
					imageDto.setSmallUrl(fileArr[ii]);
					imageDto.setImgType("6");
					imageDto.setMerchantId(user.getMerchantId());
					imageDto.setUserCode(user.getUserCode());
					imageDto.setAccessCode(projectCode);
					imageDto.setCreateUserId(user.getId());
					imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					imageServiceFacade.save(imageDto);
				} catch (NumberFormatException e) {
	
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 方法描述 : 详情 创建者：ThinkPad 项目名称： emm-website 类名： BusinessAbnormaController.java 版本： v1.0 创建时间： 2016年7月12日 下午4:14:29
	 * 
	 * @param id
	 * @return ModelAndView
	 */
	@RequestMapping(value = "businessDetail")
	public String businessDetail(ModelMap map, Long id, String procInstId, String processFlag,String back, HttpServletRequest request) {
		//是否是新换房业务
		Response<SubscribeInfo> response = subscribeServiceFacade.findByIdInfo(id);
		SubscribeInfo subscribe = response.getEntity();
		JSONObject estateRecord =  null;
		SubscribeDto querysubscribe = new SubscribeDto();
		querysubscribe.setOldId(id);
		querysubscribe.setDelFlag(DelFlagEnum.UNDEL.getNo());
		querysubscribe.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
		if(StringUtils.isNotBlank(procInstId)) {
			//querysubscribe.setProcInstId(procInstId);
			querysubscribe.setAuditStatus(null);
		}
		ResponseList<Subscribe> subList = subscribeServiceFacade.getBusinessDetailByOldId(querysubscribe);
		String subscribeStr = null;
		if(subList.isSuccess()&&subList.getEntity()!=null){ //兼容历史数据
			map.put("oldSubId", id);
			Subscribe objsub = subList.getEntity().get(0);
			id = objsub.getId();
			procInstId=objsub.getProcInstId();
			estateRecord = oaDataService.getEstateRecord(objsub.getRoomId());
			subscribeStr = JSON.toJSONString(oaDataService.getsubscribeRecord(objsub.getId()));
		}else{
			BusinessAbnormaDto abnormaDto = new BusinessAbnormaDto();
			abnormaDto.setBusinessId(id);
			abnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
			ResponseList<BusinessAbnorma> abResponseList = businessAbnormaServiceFacade.findByDto(abnormaDto);
			if(abResponseList.isSuccess()&&abResponseList.getEntity()!=null){
				BusinessAbnorma businessAbnorma  = abResponseList.getEntity().get(0);
				map.put("oldSubId", id);
				procInstId = businessAbnorma.getProcInstId();
				estateRecord = oaDataService.getEstateRecord(businessAbnorma.getNewRoomId());
				subscribeStr = JSON.toJSONString(oaDataService.getsubscribeRecord(id));
			}
		}
		JSONObject object = JSONObject.parseObject(subscribeStr);
		subscribeStr = JSON.toJSONString(object);
		map.put("subscribeRecord", subscribeStr);
		
		estateRecord.put("calculateArea", subscribe.getCalculateArea());
		estateRecord.put("unitPrice", subscribe.getConversionPrice());
		estateRecord.put("totalPrice", subscribe.getLumpsumPrice());
		map.put("estateRecord", estateRecord.toJSONString());
		User user = ShiroUtil.getCurrentUser();
	
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));

		if (response.isSuccess()) {
			//根据旧认购ID,获取换房后的换房中间记录
			SubscribeDto subDto = new SubscribeDto();
			subDto.setOldId(subscribe.getId());
			ResponseList<Subscribe> subResList = subscribeServiceFacade.findByDto(subDto);
			Subscribe changeSub = subscribe;
			if(subResList.isSuccess() && null != subResList.getEntity() && subResList.getEntity().size() > 0) {
				for(Subscribe sub: subResList.getEntity()) {
					if(SubscribeBusinessStatusEnum.HAVEWARDS.getNo().equals(sub.getBusinessStatus())
						&& SubscribeBusinessStatusEnum.HAVEWARDS.getNo().equals(sub.getBusinessSecStatus())) {
						changeSub = sub;
					}
				}
			}
			map.put("auditStatus", changeSub.getAuditStatus());
			map.put("procInstId", StringUtils.isBlank(procInstId)?changeSub.getProcInstId():procInstId);
			if(null != changeSub) {
				map.put("procInstId", changeSub.getProcInstId());
			}
			
			map.put("businessStatus", subscribe.getBusinessStatus());
			JSONObject customerRecord = oaDataService.getCustomerRecord(subscribe.getCustomerId());
			map.put("customerRecord", customerRecord.toJSONString());
			map.put("userName", subscribe.getUserName());
		}
		map.put("documentType", dtArray.toJSONString());
		map.put("processFlag", processFlag != null ? processFlag : "false");
		map.put("subscribeId", id);
		map.put("back", back);
		return "/marketing/abnorma/subscribeChangeRoomView";
	}

	/**
	 * 方法描述 : 详情数据异步加载 创建者：ThinkPad 项目名称： emm-website 类名： BusinessAbnormaController.java 版本： v1.0 创建时间： 2016年7月12日
	 * 下午4:53:09
	 * 
	 * @param id
	 * @return ExtResultVo
	 */
	@RequestMapping(value = "loadDetailById")
	public @ResponseBody
	ExtResultVo loadDetailById(Long id) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		vo.setData(businessAbnormaServiceFacade.findAbormaBusinessDetailById(id));
		return vo;
	}
	/**
	 * 
	 * getBuinessAbnormaByBuinessId:(验证流程发起正确性). <br/>
	 * @author Administrator
	 * @param buinessId
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "getBuinessAbnormaByBuinessId")
	public @ResponseBody AjaxRes getBuinessAbnormaByBuinessId(Long buinessId){
		AjaxRes ajaxRes = getAjaxRes();
		BusinessAbnormaDto queryDto = new BusinessAbnormaDto();
		User user = ShiroUtil.getCurrentUser();
		queryDto.setMerchantId(user.getMerchantId());
		queryDto.setBusinessId(buinessId);
		queryDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
		ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade.findByDto(queryDto);
		if(responseList.isSuccess()&&responseList.getEntity()!=null){
			BusinessAbnorma businessAbnorma = responseList.getEntity().get(0);
			BusinessAbnormaEnum businessEnum = BusinessAbnormaEnum.getByNo(businessAbnorma.getBusinessType());
			ajaxRes.setResMsg("【"+businessEnum.getName()+"】,正在审核中,请尽快审批!");
		}else{
			ajaxRes.setRes(Const.SUCCEED);
		}
		return ajaxRes;
	}
	@RequestMapping(value = "vaildBuiness")
	public @ResponseBody AjaxRes vaildBuiness(Long roomId){
		AjaxRes ajaxRes = getAjaxRes();
		ActNodeQuery actQuery = new ActNodeQuery();
		actQuery.setRoomId(roomId);
		List<ActNodeDataDto> actNodeList = actNodeDataServiceFacade.queryActByRoomId(actQuery).getEntity();
		if(actNodeList!=null){
			ActNodeDataDto actNode = actNodeList.get(0);
			ajaxRes.setRes(Const.FAIL);
			ajaxRes.setResMsg("房间:【"+actNode.getRoomName()+"】,正在"+actNode.getProcessDefinitionName());
		}else{
			ajaxRes.setRes(Const.SUCCEED);
		}
		return ajaxRes;
	}
	

}
